package com.cmccgz.udacs_landlord_webapp.main.web;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.cmccgz.baselibrary.base.BaseActivity;
import com.cmccgz.baselibrary.base.PermissionUtils;
import com.cmccgz.baselibrary.utils.StringUtils;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.base.ApiService;
import com.cmccgz.udacs_landlord_webapp.bean.IdBean;
import com.cmccgz.udacs_landlord_webapp.bean.WebConfig;
import com.cmccgz.udacs_landlord_webapp.data.IdScanDataRepository;
import com.cmccgz.udacs_landlord_webapp.data.IdScanDataSource;
import com.google.gson.Gson;
import com.just.library.AgentWeb;
import com.just.library.ChromeClientCallbackManager;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import rx.Subscriber;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static com.bilibili.boxing.AbsBoxingViewFragment.CAMERA_PERMISSIONS;


public class NWebActivity extends BaseActivity implements View.OnClickListener, ChromeClientCallbackManager.ReceivedTitleCallback {

    //    private ViewHelper mViewHelper;
    private LinearLayout ll_conarnter;
    private AgentWeb mAgentWeb;
    public final static String KEY_CONFIG = "key_config";
    private WebConfig webConfig;
    private IdScanDataRepository idScanDataRepository;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_web_n;
    }

    @Override
    protected void initView() {
//        mViewHelper = ViewHelper.instance(this);
//        mViewHelper.setAllVisable(false);
//        mViewHelper.setBackTextVisable(true);
        initDatas();
        ll_conarnter = ((LinearLayout) findViewById(R.id.ll_contarnter));
        String url = webConfig == null ? "" : webConfig.getUrl();
        Log.e("INX", "NWebActivity: url=" + url);
        mAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent(ll_conarnter, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))//
                .useDefaultIndicator()// 使用默认进度条
                .defaultProgressBarColor() // 使用默认进度条颜色
                .setReceivedTitleCallback(this) //设置 Web 页面的 title 回调
                .createAgentWeb()//
                .ready()
                .go(url);
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface(NWebActivity.this));
    }

    private void initDatas() {
        webConfig = ((WebConfig) getIntent().getSerializableExtra(KEY_CONFIG));
        if (webConfig == null) {
            onBackPressed();
            ToastUtils.show(mContext, "url不能为空！");
        }
    }

    @Override
    protected void initFragment() {

    }

    @Override
    protected void beforePermission() {

    }

    @Override
    protected int setSystemBarColorId() {
        return 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                onBackPressed();
                break;
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
//        if (webConfig != null && !StringUtils.isEmpty(webConfig.getTitle())) {
//            mViewHelper.setTitle(webConfig.getTitle());
//            return;
//        }
//        mViewHelper.setTitle(title);
    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        JZVideoPlayer.releaseAllVideos();
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        mAgentWeb.clearWebCache();
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    private class AndroidInterface extends Object {
        private NWebActivity context;

        public AndroidInterface(NWebActivity context) {
            this.context = context;
        }

        @JavascriptInterface
        public void scanIdCard() {
            PermissionUtils.askPermission(NWebActivity.this, 101, callBack, Manifest.permission.CAMERA);
        }

        @JavascriptInterface
        public void finish() {
            context.finish();
        }

        @JavascriptInterface
        public void playVideo(final String url) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    playVideoOnMain(url);
                }
            });
        }

        private void playVideoOnMain(String url) {
            showLoadingDialog("正在加载视频...");
            if (TextUtils.isEmpty(url)){
                getVideoUrlError("该视频为空，请稍后再试!");
                return;
            }
            final File file = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "cmccgz" + File.separator + "vCache", getFileName(url));
            if (file.exists() && file.length() != 0) {
                getVideoUrlSuccess(file.getAbsolutePath());
                return;
            }
            ApiService.downFile(url, file).subscribe(new Subscriber<Boolean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    getVideoUrlError("加载视频失败!");
                }

                @Override
                public void onNext(Boolean aBoolean) {
                    if (!aBoolean || !file.exists()) {
                        onError(null);
                        return;
                    }
                    if (file.length() == 0) {
                        getVideoUrlError("该视频为空，请稍后再试!");
                        return;
                    }
                    getVideoUrlSuccess(file.getAbsolutePath());
                }
            });
        }
    }

    private void getVideoUrlError(String s) {
        dismissLoadingDialog();
        ToastUtils.show(mContext, s);
    }

    private void getVideoUrlSuccess(String absolutePath) {
        dismissLoadingDialog();
        JZVideoPlayerStandard.startFullscreen(this, JZVideoPlayerStandard.class, absolutePath, "开门视频");
    }

    @NonNull
    private String getFileName(String videoUrl, String endName) {
        int index = videoUrl.lastIndexOf("/");
        Pattern p = Pattern.compile("[0-9a-zA-Z]+");
        String substring = videoUrl.substring(index);
        Matcher matcher = p.matcher(substring);
        String fileName = "";
        while (matcher.find()) {
            fileName += matcher.group();
        }
        endName = com.cmccgz.udacs_landlord_webapp.update.StringUtils.isEmpty(endName) ? "" : ("." + endName);
        return fileName + endName;
    }

    @NonNull
    private String getFileName(String videoUrl) {
        return getFileName(videoUrl, null);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 101) {
            PermissionUtils.handlePermissionRequest(permissions, grantResults, this, callBack, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }

            });
        }
    }

    private final static int REQUEST_CAMERA = 102;

    private String picPath;
    private PermissionUtils.PermissionAskCallback callBack = new PermissionUtils.PermissionAskCallback() {
        @Override
        public void hasPermissionDoNext() {
            if (ContextCompat.checkSelfPermission(mContext, CAMERA_PERMISSIONS[0]) != PERMISSION_GRANTED) {
                ToastUtils.show(mContext, "请开启摄像头权限！");
                return;
            }

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "cmccgz", System.currentTimeMillis() + ".jpg");
            picPath = file.getAbsolutePath();
            Uri uri = Uri.fromFile(new File(picPath));
            //为拍摄的图片指定一个存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_CAMERA);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == CODE_REQUEST && resultCode == HouseListActivity.RESULT_CODE) {
//            String house_name = data.getStringExtra(HouseListActivity.HOUSE_NAME);
//            String house_id = data.getStringExtra(HouseListActivity.HOUSE_ID);
//            et_house.setText(house_name);
//            et_house.setTag(house_id);
//        }
        if (resultCode == RESULT_OK
                && requestCode == REQUEST_CAMERA
                && !StringUtils.isEmpty(picPath)
                && new File(picPath).exists()) {
            showLoadingDialog("正在解析身份证信息...");
            //解析
//            mPresenter.scanId(picPath);
            if (idScanDataRepository == null) {
                idScanDataRepository = new IdScanDataRepository();
            }
            idScanDataRepository.scanId(picPath, new IdScanDataSource.IdScanLisenter() {
                @Override
                public void scanIdSuccess(IdBean idBean) {
                    if (idBean == null) {
                        mAgentWeb.getJsEntraceAccess().quickCallJs("getInfoMation", "");
                    } else {
                        Gson gson = new Gson();
                        String json = gson.toJson(idBean);
                        System.out.println(json);
                        mAgentWeb.getJsEntraceAccess().quickCallJs("getInfoMation", json);
                    }
                    //删除图片
                    boolean delete = new File(picPath).delete();
                    Log.e("INX", "scanIdSuccess: 删除文件：" + picPath + (delete ? "  成功" : "失败"));
                    dismissLoadingDialog();
                }

                @Override
                public void scanIdError(String msg) {
                    mAgentWeb.getJsEntraceAccess().quickCallJs("getInfoMation", "");
                    dismissLoadingDialog();
                }
            });
        }
    }

}
